package com.atom.app.mvi

import androidx.multidex.MultiDexApplication
import com.atom.app.mvi.ui.SplashActivity
import com.atom.module.logger.Logger
import com.atom.module.mvi.binder.middleware.config.MiddlewareConfiguration
import com.atom.module.mvi.binder.middleware.config.Middlewares
import com.atom.module.mvi.binder.middleware.config.WrappingCondition
import com.atom.module.mvi.core.consumer.middleware.LoggingMiddleware
import com.atom.module.mvi.core.consumer.middleware.PlaybackMiddleware
import com.atom.module.mvi.core.consumer.playback.MemoryRecordStore
import com.atom.module.mvi.plugin.middleware.DefaultPluginStore
import com.atom.module.mvi.plugin.middleware.IdeaPluginMiddleware
import com.atom.module.reporter.CrashReporter
import com.tencent.mmkv.MMKV
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers

class App : MultiDexApplication() {

    companion object {

        private lateinit var instance: App

        fun getApp(): App {
            return instance
        }
    }
    override fun onCreate() {
        super.onCreate()
        instance = this
        // Logger init
        Logger.init(isDebug = true)
        // CrashReport
        CrashReporter.initialize(this)
        CrashReporter.setRestartActivity(SplashActivity::class.java)
        CrashReporter.setReportHandler { error, callback ->
            Logger.e(error)
            callback.onCallback("Success")
        }
        // MMKV Init
        MMKV.initialize(this)

        // middle
        // middlewares()
    }

    private fun middlewares() {
        Middlewares.configurations.add(
            MiddlewareConfiguration(condition = WrappingCondition.Always,
                factories = listOf { consumer -> LoggingMiddleware(consumer, { Logger.d(it) }) })
        )

        Middlewares.configurations.add(
            MiddlewareConfiguration(condition = WrappingCondition.AllOf(
                WrappingCondition.Conditional { BuildConfig.DEBUG }, WrappingCondition.AnyOf(
                    WrappingCondition.IsNamed, WrappingCondition.IsStandalone
                )
            ), factories = listOf { consumer ->
                PlaybackMiddleware(consumer, recordStore, { Logger.d(it) })
            })
        )

        Middlewares.configurations.add(
            MiddlewareConfiguration(
                condition = WrappingCondition.Always,
                factories = listOf({ consumer -> IdeaPluginMiddleware(consumer, defaultStore) })
            )
        )
    }



    private val recordStore: PlaybackMiddleware.RecordStore = MemoryRecordStore(
        playbackScheduler = AndroidSchedulers.mainThread(),
        logger = { Logger.d(it) })

    private val defaultStore = DefaultPluginStore(BuildConfig.APPLICATION_ID)


}
